package com.kongjs.common.security.util;

import cn.hutool.core.lang.tree.Tree;

import java.util.*;

public class TreesUtil {

    // 获取每个节点的所有层级子节点（递归子节点）
    public static <T> Map<T, List<Tree<T>>> getAllRecursiveChildrenMap(List<Tree<T>> rootNodes) {
        Map<T, List<Tree<T>>> resultMap = new HashMap<>();
        Stack<Tree<T>> stack = new Stack<>();

        // 初始化栈
        for (Tree<T> root : rootNodes) {
            stack.push(root);
        }

        while (!stack.isEmpty()) {
            Tree<T> currentNode = stack.pop();
            T currentId = currentNode.getId();

            // 为当前节点初始化子节点列表
            resultMap.putIfAbsent(currentId, new ArrayList<>());

            // 递归收集当前节点的所有子节点
            collectRecursiveChildren(currentNode, resultMap.get(currentId));

            // 处理子节点
            List<Tree<T>> children = currentNode.getChildren();
            if (children != null) {
                for (int i = children.size() - 1; i >= 0; i--) {
                    stack.push(children.get(i));
                }
            }
        }

        return resultMap;
    }

    // 递归收集所有子节点（内部使用）
    private static <T> void collectRecursiveChildren(Tree<T> node, List<Tree<T>> resultList) {
        List<Tree<T>> children = node.getChildren();
        if (children != null) {
            for (Tree<T> child : children) {
                resultList.add(child);
                collectRecursiveChildren(child, resultList);
            }
        }
    }
}
